using System;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Diagnostics;
using WPF_MVVM_Test.MVVM_Model;

namespace WPF_MVVM_Test.Services
{
    public class MesAiService
    {
        private readonly HttpClient _httpClient;
        private const string MES_AI_BASE_URL = "http://101.200.57.145:8888/api/LangChain";
        private const string MES_AI_HEALTH_CHECK_URL = MES_AI_BASE_URL + "/health-check";
        private const string MES_AI_QUICK_SEND_URL = MES_AI_BASE_URL + "/quick-send";

        public MesAiService()
        {
            _httpClient = new HttpClient();
            _httpClient.DefaultRequestHeaders.Add("accept", "application/json");
            _httpClient.Timeout = TimeSpan.FromMinutes(5); // 设置为5分钟
        }

        /// <summary>
        /// 检查MES AI服务健康状态
        /// </summary>
        /// <returns>服务是否可用</returns>
        public async Task<bool> CheckHealthAsync()
        {
            try
            {
                Debug.WriteLine("检查MES AI服务健康状态...");

                // 创建一个专门用于健康检查的HttpClient，设置较长的超时时间
                using var healthCheckClient = new HttpClient();
                healthCheckClient.Timeout = TimeSpan.FromMinutes(2); // 健康检查超时2分钟
                healthCheckClient.DefaultRequestHeaders.Add("accept", "application/json");

                using var response = await healthCheckClient.GetAsync(MES_AI_HEALTH_CHECK_URL);

                if (response.IsSuccessStatusCode)
                {
                    var responseText = await response.Content.ReadAsStringAsync();
                    Debug.WriteLine($"健康检查响应: {responseText}");

                    // 尝试解析为布尔值
                    if (bool.TryParse(responseText.Trim().Trim('"'), out bool isHealthy))
                    {
                        Debug.WriteLine($"MES AI服务健康状态: {isHealthy}");
                        return isHealthy;
                    }

                    // 如果不是布尔值，检查是否包含成功标识
                    var isHealthyByContent = responseText.Contains("true", StringComparison.OrdinalIgnoreCase);
                    Debug.WriteLine($"MES AI服务健康状态（通过内容判断）: {isHealthyByContent}");
                    return isHealthyByContent;
                }

                Debug.WriteLine($"健康检查失败: {response.StatusCode} - {response.ReasonPhrase}");
                return false;
            }
            catch (TaskCanceledException ex) when (ex.InnerException is TimeoutException)
            {
                Debug.WriteLine("健康检查超时");
                return false;
            }
            catch (TaskCanceledException ex)
            {
                Debug.WriteLine($"健康检查被取消: {ex.Message}");
                return false;
            }
            catch (HttpRequestException ex)
            {
                Debug.WriteLine($"健康检查网络异常: {ex.Message}");
                return false;
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"健康检查异常: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 测试API连接
        /// </summary>
        public async Task<bool> TestApiConnectionAsync()
        {
            try
            {
                Debug.WriteLine("=== 测试MES AI API连接 ===");
                Console.WriteLine("=== 测试MES AI API连接 ===");

                // 先测试健康检查
                var healthResult = await CheckHealthAsync();
                Debug.WriteLine($"健康检查结果: {healthResult}");
                Console.WriteLine($"健康检查结果: {healthResult}");

                if (!healthResult)
                {
                    Debug.WriteLine("健康检查失败，API可能不可用");
                    Console.WriteLine("健康检查失败，API可能不可用");
                    return false;
                }

                // 测试一个简单的请求 - 发送JSON字符串格式
                var testUrl = MES_AI_QUICK_SEND_URL + "?userId=test123";
                var testMessage = "测试连接";
                var content = new StringContent($"\"{testMessage}\"", Encoding.UTF8, "application/json");

                Debug.WriteLine($"测试请求URL: {testUrl}");
                Debug.WriteLine($"测试请求内容: {testMessage}");
                Console.WriteLine($"测试请求URL: {testUrl}");
                Console.WriteLine($"测试请求内容: {testMessage}");

                using var response = await _httpClient.PostAsync(testUrl, content);
                Debug.WriteLine($"测试响应状态码: {response.StatusCode}");
                Console.WriteLine($"测试响应状态码: {response.StatusCode}");

                var responseContent = await response.Content.ReadAsStringAsync();
                Debug.WriteLine($"测试响应内容: {responseContent}");
                Console.WriteLine($"测试响应内容: {responseContent}");

                return response.IsSuccessStatusCode;
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"API连接测试失败: {ex.Message}");
                Console.WriteLine($"API连接测试失败: {ex.Message}");
                Console.WriteLine($"异常详情: {ex}");

                // 显示详细错误信息
                System.Windows.MessageBox.Show($"API连接测试失败:\n\n错误信息: {ex.Message}\n\n详细信息: {ex}",
                    "连接测试失败",
                    System.Windows.MessageBoxButton.OK,
                    System.Windows.MessageBoxImage.Error);

                return false;
            }
        }

        public async Task SendMessageAsync(MesAiRequest request, string? userId, Action<string> onDataReceived, Action onCompleted, Action<Exception> onError)
        {
            try
            {
                Debug.WriteLine($"=== MES AI 请求开始 ===");
                Debug.WriteLine($"发送MES AI请求: {JsonSerializer.Serialize(request)}");

                // 构建URL，添加userId查询参数
                var url = MES_AI_QUICK_SEND_URL;
                if (!string.IsNullOrEmpty(userId))
                {
                    url += $"?userId={Uri.EscapeDataString(userId)}";
                }

                // 根据API错误信息，服务器期望的是一个简单的字符串，而不是JSON对象
                // 尝试直接发送消息内容作为JSON字符串
                var content = new StringContent($"\"{request.Content}\"", Encoding.UTF8, "application/json");

                Debug.WriteLine($"请求URL: {url}");
                Debug.WriteLine($"请求内容: \"{request.Content}\"");
                Debug.WriteLine($"Content-Type: application/json");
                Debug.WriteLine($"HttpClient Timeout: {_httpClient.Timeout}");

                // 发送API请求
                Debug.WriteLine("开始发送HTTP请求...");
                using var response = await _httpClient.PostAsync(url, content);
                Debug.WriteLine($"收到HTTP响应，状态码: {response.StatusCode}");

                if (!response.IsSuccessStatusCode)
                {
                    var errorContent = await response.Content.ReadAsStringAsync();
                    Debug.WriteLine($"MES AI API请求失败: {response.StatusCode}, 内容: {errorContent}");
                    onError?.Invoke(new Exception($"API请求失败: {response.StatusCode}, 内容: {errorContent}"));
                    return;
                }

                // 读取响应内容
                var responseText = await response.Content.ReadAsStringAsync();
                Debug.WriteLine($"MES AI API响应: {responseText}");

                if (string.IsNullOrWhiteSpace(responseText))
                {
                    Debug.WriteLine("MES AI API返回空响应");
                    onError?.Invoke(new Exception("服务器返回空响应"));
                    return;
                }

                // 尝试解析为 MesAiResponse 对象
                try
                {
                    var mesAiResponse = JsonSerializer.Deserialize<MesAiResponse>(responseText);

                    if (mesAiResponse != null)
                    {
                        // 检查是否成功
                        if (!mesAiResponse.Success)
                        {
                            var errorMessage = !string.IsNullOrEmpty(mesAiResponse.ErrorMessage)
                                ? mesAiResponse.ErrorMessage
                                : "未知错误";

                            Debug.WriteLine($"MES AI API返回失败: {errorMessage}");
                            onError?.Invoke(new Exception($"API返回失败: {errorMessage}"));
                            return;
                        }

                        // 提取内容
                        if (!string.IsNullOrEmpty(mesAiResponse.Content))
                        {
                            Debug.WriteLine($"MES AI提取的内容: {mesAiResponse.Content}");
                            onDataReceived?.Invoke(mesAiResponse.Content);
                            onCompleted?.Invoke();
                            return;
                        }
                    }

                    // 如果无法从对象中获取内容，尝试直接解析JSON
                    var jsonDoc = JsonDocument.Parse(responseText);
                    Debug.WriteLine($"MES AI解析的JSON: {jsonDoc.RootElement}");

                    // 尝试从JSON中提取内容
                    if (jsonDoc.RootElement.TryGetProperty("content", out var contentProp))
                    {
                        var extractedContent = contentProp.GetString();
                        if (!string.IsNullOrEmpty(extractedContent))
                        {
                            Debug.WriteLine($"MES AI从JSON提取的内容: {extractedContent}");
                            onDataReceived?.Invoke(extractedContent);
                            onCompleted?.Invoke();
                            return;
                        }
                    }

                    // 如果仍然无法提取内容，返回默认消息
                    Debug.WriteLine("MES AI无法提取内容，返回默认消息");
                    onDataReceived?.Invoke("抱歉，我无法理解服务器的响应。");
                }
                catch (JsonException ex)
                {
                    // JSON解析失败，返回错误消息
                    Debug.WriteLine($"MES AI JSON解析失败: {ex.Message}");
                    onDataReceived?.Invoke("抱歉，服务器返回的数据格式有误。");
                }

                onCompleted?.Invoke();
            }
            catch (HttpRequestException ex)
            {
                Debug.WriteLine($"=== MES AI HTTP请求异常 ===");
                Debug.WriteLine($"异常类型: HttpRequestException");
                Debug.WriteLine($"异常消息: {ex.Message}");
                Debug.WriteLine($"内部异常: {ex.InnerException?.Message}");
                onError?.Invoke(ex);
            }
            catch (TaskCanceledException ex) when (ex.InnerException is TimeoutException)
            {
                Debug.WriteLine($"=== MES AI 请求超时 ===");
                Debug.WriteLine($"超时时间: {_httpClient.Timeout}");
                onError?.Invoke(new TimeoutException("请求超时，请检查网络连接或稍后重试"));
            }
            catch (TaskCanceledException ex)
            {
                Debug.WriteLine($"=== MES AI 请求被取消 ===");
                Debug.WriteLine($"异常消息: {ex.Message}");
                onError?.Invoke(new Exception("请求被取消"));
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"=== MES AI 未知异常 ===");
                Debug.WriteLine($"异常类型: {ex.GetType().Name}");
                Debug.WriteLine($"异常消息: {ex.Message}");
                Debug.WriteLine($"堆栈跟踪: {ex.StackTrace}");
                onError?.Invoke(ex);
            }
        }

        public void Dispose()
        {
            _httpClient?.Dispose();
        }
    }
}
